import java.util.Map;
import java.util.Scanner;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2025-06-29
 * Time: 22:57
 */
public class Test7 {
    public static int trap(int[] height) {
        Stack<Integer> st = new Stack<>();
        if(height.length < 2) {
            return 0;
        }
        int ret = 0;
        for(int i = 0; i < height.length; i++) {
            while(!st.isEmpty() && height[i] > height[st.peek()]) {
                int mid = st.pop();
                if(!st.isEmpty()) {
                    int left = st.peek();
                    ret += (Math.min(height[left],height[i]) - height[mid]) * (i-left-1);
                }
            }
            st.push(i);
        }
        return ret;
    }


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] num = new int[n];
        for(int i = 0; i < n; i++) {
            num[i] = sc.nextInt();
        }
        int ret = trap(num);
        System.out.println(ret);
    }
}
